<template>
  <!-- 故障类型统计 -->
  <div class="page-container">
    <div class="control-container">
      <div class="left-panel shrink-panel" :class="isWide?'':'narrow'">
        <div class="shrink-btn-panel">
          <i :class="isWide?'el-icon-arrow-left':'el-icon-arrow-right'" @click="isWide = !isWide" />
        </div>
        <OutletTree
          v-if="isWide"
          @handleNodeClick="handleNodeClick"
        />
      </div>
      <div class="right-panel">
        <div class="search-panel">
          <el-form :inline="true" label-width="100">
            <el-form-item label="开始时间：">
              <el-date-picker
                v-model="query.startTime"
                type="date"
                :clearable="false"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="结束时间：">
              <el-date-picker
                v-model="query.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                :clearable="false"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-button type="primary" @click="handleSelect">查询</el-button>
            <!-- <el-button type="primary" @click="handleExport">导出</el-button> -->
          </el-form>
        </div>
        <div>{{ name }}</div>
        <div class="table-panel">
          <el-table
            v-loading="tableLoading"
            class="grid-data-table"
            :data="tableData"
            border
          >
            <el-table-column prop="lx" label="离线（次）" />
            <el-table-column prop="lxRate" label="离线率（%）" />
            <el-table-column prop="fxygz" label="分析仪器故障（次）" />
            <el-table-column prop="fxygzRate" label="分析仪器故障数率（%）" />
            <el-table-column prop="cb" label="超标（次）" />
            <el-table-column prop="cbRate" label="超标率（%）" />
            <el-table-column prop="hz" label="恒值（次）" />
            <el-table-column prop="hzRate" label="恒值率（%）" />
          </el-table>
        </div>
        <div style="flex: 2; height:40%; width:45%; display:inline-block;">
          <div id="ech1" style="height:100%;" />
        </div>
        <div style="flex: 2; height:40%; width:45%; display:inline-block;">
          <div id="ech2" style="height:100%;" />
        </div>
        <div style="flex: 2; height:40%; width:100%; display:inline-block;">
          <div id="ech3" style="height:100%;" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'
import OutletTree from '@/components/Tree/outletTree'
import { countSatisfaction } from '@/api/base/statistics'
import { getDictLabel } from '@/utils'
import { getDatefmt } from '@/utils/common'
export default {
  name: 'FaultType',
  components: {
    OutletTree
  },
  data() {
    return {
      isWide: true,
      query: {
        projectDepartmentId: null,
        enterpriseId: null,
        outletId: null,
        startTime: '',
        endTime: ''
      },
      tableLoading: false,
      tableData: [],
      spanArr: [],
      position: 0,
      name: '全部'
    }
  },
  created() {
    this.initData()
  },
  mounted() {},
  methods: {
    getDictLabel,
    initData() {
      this.cleanQuery()
      this.setDate()
      this.handleSelect()
    },
    // 查询
    handleSelect() {
      this.tableLoading = true
      const query = JSON.parse(JSON.stringify(this.query))
      countSatisfaction(query).then(res => {
        this.tableData = [res.data.alarm]
        this.tableLoading = false
        this.inEcharts(['超标', '离线', '分析仪器故障', '恒值'], [res.data.alarm.cb, res.data.alarm.lx, res.data.alarm.fxygz, res.data.alarm.hz], 'ech1')
        this.inEcharts(['超标', '离线', '分析仪器故障', '恒值'], [res.data.alarm.cb, res.data.alarm.lx, res.data.alarm.fxygz, res.data.alarm.hz], 'ech2')
        var xDate = []
        var yDate = []
        res.data.maintenance.forEach(item => {
          xDate.push(item.shortName)
          yDate.push(item.count)
        })
        this.inEcharts3(xDate, yDate)
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 导出  未完成
    handleExport() {
      this.exportLoading = true

      import('@/utils/Export2Excel').then(excel => {
        const header = ['项目名称', '排放口名称', '运维设备名称', '服务类型', '设备型号', '设备编号', '数量/（台）'] // 最后一行的表头数据
        const filterVal = ['name', 'outletName', 'shortName', 'serverType', 'eqmModel', 'equipmentNumber', 'contacts']
        // 这里要注意 header  和 filterVal 的数组长度一定要相等，否则会报错
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        const styleRows = [1]
        const merges = [] // 合并单元格的数据，如何合并参考上面图片讲解
        for (var i = 0; i < list.length; i = j) {
          for (var j = i + 1; j < list.length; j++) {
            if (list[i].name !== list[j].name) {
              merges.push('A' + (i + 2) + ':' + 'A' + (j + 1))
              break
            } else if (j === list.length - 1) {
              merges.push('A' + (i + 2) + ':' + 'A' + (j + 2))
            }
          }
        }
        const styleColumns = [1]
        excel.export_json_to_excel({
          header,
          data,
          merges,
          styleRows,
          styleColumns,
          filename: this.name + '_设备运行情况统计'
        })
      })
      this.exportLoading = false
    },
    // 点击树
    handleNodeClick(data) {
      this.query.projectDepartmentId = null
      this.query.enterpriseId = null
      this.query.outletId = null
      this.name = data.name
      if (data.level === 1) {
        this.query.projectDepartmentId = data.id
      } else if (data.level === 2) {
        this.query.enterpriseId = data.id
      } else if (data.level === 3) {
        this.query.outletId = data.id
      }
      this.handleSelect()
    },
    cleanQuery() {
      this.query = {
        projectDepartmentId: null,
        enterpriseId: null,
        outletId: null,
        startTime: '',
        endTime: ''
      }
    },
    // 拼接数据
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    setDate() {
      const defaultTime = 30
      const date = new Date()
      this.query.endTime = getDatefmt(date, 'yyyy-MM-dd' + ' 23:59:59')
      this.query.startTime = getDatefmt(new Date(date.getTime() - 3600 * 1000 * 24 * defaultTime), 'yyyy-MM-dd' + ' 00:00:00')
    },
    inEcharts(data, series, elementId) {
      const chartDom = document.getElementById(elementId)
      const myChart = echarts.init(chartDom)
      var scale = 1
      console.log(data, series)
      const echartData = []
      data.map((label, i) => {
        echartData.push({
          value: series[i],
          name: label
        })
      })
      var rich = {
        yellow: {
          color: '#3bc7ff',
          fontSize: 14 * scale,
          padding: [8, 0],
          align: 'center'
        },
        total: {
          color: '#A2C7F3',
          fontSize: 60 * scale,
          align: 'center'
        },
        white: {
          color: '#a2c7f3',
          align: 'center',
          fontSize: 18 * scale,
          padding: [8, 0]
        },
        blue: {
          color: '#3bc7ff',
          fontSize: 18 * scale,
          align: 'center'
        },
        hr: {
          borderColor: '#a2c7f3',
          width: '100%',
          borderWidth: 1,
          height: 0
        }
      }
      const option = {
        backgroundColor: '',
        series: [{
          name: '数量',
          type: 'pie',
          radius: ['45%', '60%'],
          hoverAnimation: false,
          color: ['#fc962c', '#d83472', '#0F9AF8', '#2B63D5', '#2039C3', '#2ECACE', '#6F81DA'],
          label: {
            normal: {
              formatter: function(params, ticket, callback) {
                var total = 0 // 考生总数量
                var percent = 0 // 考生占比
                echartData.forEach(function(value, index, array) {
                  total += value.value
                })
                percent = ((params.value / total) * 100).toFixed(1)
                return '{darkblue|' + params.name + '}(' + params.value + ')\n{blue|' + percent + '%}'
              },
              rich: rich
            }
          },
          labelLine: {
            normal: {
              length: 15,
              length2: 6,
              lineStyle: {
                color: '#a2c7f3'
              }
            }
          },
          data: echartData
        }]
      }
      myChart.setOption(option)
    },
    inEcharts3(xData, yDate) {
      var chartDom = document.getElementById('ech3')
      var myChart = echarts.init(chartDom)
      var option

      option = {
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: yDate,
            type: 'bar',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      }

      option && myChart.setOption(option)
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
